//
//  UUKeeperEditVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 02/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUKeeperEditVC.h"
#import "UUHybridManager+CharterSupplier.h"
#import "UUKeeperManager.h"
#import "UUFleetManager.h"
#import "UUPermissionManager.h"
#import "UUPermissionUtility.h"
#import <UUFoundation/DKProgressHUD.h>

@interface UUKeeperEditVC () <UUKeeperManagerObserver>

@end

@implementation UUKeeperEditVC

- (void)viewDidLoad {
    if (!self.editable) {
        [GetKeeperManager() addObserver:self];
    }
    
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *)name {
    return @"管理员";
}

- (BOOL)isAdd {
    return self.keeperId == nil;
}

- (BOOL)canEdit {
    if (self.keeperId != nil) {
        if ([GetKeeperManager() fetchKeeperWithKeeperId:self.keeperId].roleId == UUPermissionRoleTypeOwner) {
            return NO;
        } else {
            return [GetPermissionManager() checkPermission:UUPermissionFlagKeeperReadWrite];
        }
    } else {
        return [GetPermissionManager() checkPermission:UUPermissionFlagKeeperReadWrite];
    }
}

- (NSURLRequest *)editRequest {
    return GetHybridManager().keeperEditURLRequest;
}

- (NSURLRequest *)detailRequest {
    return GetHybridManager().keeperDetailURLRequest;
}

- (void)configEditVC:(UUKeeperEditVC *)editVC {
    editVC.keeperId = self.keeperId;
}

- (void)addOrUpdate:(NSDictionary *)data {
    id fleetIds = data[@"motorcade_ids"];
    UUPermissionRoleType roleId = [data[@"role_id"] integerValue];
    NSString *name = data[@"name"];
    NSString *mobile = data[@"mobile"];
    
    WEAK_SELF();
    void (^completeBlock)(NSError *error) = ^(NSError *error) {
        HideTipsOnView(weakSelf.view);
        
        if (error) {
            ShowTipsOnView(error.localizedDescription, weakSelf.view);
        } else {
            NSString *tips = [NSString stringWithFormat:@"%@成功", weakSelf.keeperId == nil ? @"添加" : @"更新"];
            ShowTipsInKeyWindow(tips);
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    };
    
    ShowIndicator();
    
    if (self.keeperId == nil) {
        [GetKeeperManager() asyncAddKeeperWithName:name
                                            mobile:mobile
                                          fleetIds:fleetIds
                                            roleId:roleId
                                     completeBlock:completeBlock];
    } else {
        [GetKeeperManager() asyncUpdateKeeperWithKeeperId:self.keeperId
                                                     name:name
                                                   mobile:mobile
                                                 fleetIds:fleetIds
                                                   roleId:roleId
                                            completeBlock:completeBlock];
    }
}

- (NSDictionary *)previewFields {
    if (self.keeperId != nil) {
        UUKeeperModel *keeper = [GetKeeperManager() fetchKeeperWithKeeperId:self.keeperId];
        return @{
                 @"id" : self.keeperId,
                 @"name" : keeper.name,
                 @"mobile" : keeper.mobile,
                 @"role_id" : @(keeper.roleId),
                 @"role_name" : [UUPermissionUtility roleNameForRoleId:keeper.roleId],
                 @"motorcade_ids" : keeper.fleetIds ?: @"",
                 @"motorcade_name" : [self fleetNamesForFleetIds:keeper.fleetIds],
                 };
    } else {
        return nil;
    }
}

- (NSString *)fleetNamesForFleetIds:(NSString *)fleetIds {
    NSArray *fleetIdsArray = [fleetIds componentsSeparatedByString:@","];
    NSMutableString *fleetNames = [NSMutableString new];
    for (NSNumber *fleetId in fleetIdsArray) {
        UUFleetModel *fleet = [GetFleetManager() fetchFleetWithFleetId:fleetId];
        if (fleet) {
            if (fleetNames.length > 0) {
                [fleetNames appendString:@","];
            }
            
            [fleetNames appendString:fleet.name];
        }
    }
    
    return fleetNames;
}

#pragma mark - methods

- (void)keeperManagerDidUpdateKeepers {
    if (self.keeperId != nil) {
        [self reloadForm];
    }
}

@end
